<template>
  <!-- 卡片 -->
  <el-card class="box-card">
    <!-- 标题 -->
    <template #header>
      <div class="card-header">
        <span>{{ $route.meta.title }}</span>
      </div>
    </template>
    <!-- 上方按钮 -->
    <el-button type="primary" icon="Plus" @click="addTrademark">
      添加品牌
    </el-button>
    <!-- 表格 -->
    <el-table style="width: 100%; margin: 10px 0" border :data="trademark">
      <el-table-column label="序号" width="80" align="center" type="index" />
      <el-table-column label="品牌名称" prop="tmName" />
      <el-table-column label="品牌LOGO">
        <template #="{ row }">
          <img :src="row.logoUrl" style="width: 100px; height: 100px" />
        </template>
      </el-table-column>
      <el-table-column label="品牌操作">
        <template #="{ row }">
          <el-button
            type="primary"
            size="small"
            icon="Edit"
            @click="updateTrademark(row)"
          ></el-button>
          <el-popconfirm
            :title="`你确定要删除‘${row.tmName}’这个品牌吗`"
            @confirm="deleteTrademark(row.id)"
          >
            <template #reference>
              <el-button type="primary" size="small" icon="Delete"></el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器 -->
    <el-pagination
      :pager-count="10"
      @current-change="changeCurrenPage"
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[3, 5, 7, 9]"
      :background="true"
      layout="prev, pager, next, jumper, ->,sizes, total"
      :total="total"
    />
  </el-card>

  <!-- 对话框 -->
  <el-dialog
    v-model="dialogFormVisible"
    :title="addedTrademark.id ? '修改品牌' : '添加品牌'"
  >
    <el-form
      label-width="80px"
      :inline="false"
      size="normal"
      style="width: 80%"
      ref="ruleFormRef"
      :model="addedTrademark"
      :rules="trademarkRules"
    >
      <!-- 品牌名称 -->
      <el-form-item label="品牌名称" label-width="100px" prop="tmName">
        <el-input
          placeholder="请你输入品牌名称"
          v-model="addedTrademark.tmName"
        ></el-input>
      </el-form-item>
      <!-- 品牌LOGO -->
      <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
        <!-- 路径需要带上api，因为代理服务器认api帮我们转发 -->
        <el-upload
          class="avatar-uploader"
          action="/api/admin/product/fileUpload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img
            v-if="addedTrademark.logoUrl"
            :src="addedTrademark.logoUrl"
            class="avatar"
          />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" size="default" @click="cancel">取消</el-button>
      <el-button type="primary" size="default" @click="confirm">确认</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
//路由跳转
import { useRoute } from 'vue-router'
//vue3自带用于响应式的函数
import { ref, onMounted, watch, reactive } from 'vue'
//获取品牌数据
import {
  reqTradeMark,
  addOrUpdateTrademark,
  reqDeleteTrademark,
} from '@/api/product/trademark'
//品牌相关的自定义数据类型
import type { TrademarkResponseData, recordsDataType } from '@/api/product/type'
//用于上传图片的钩子函数数据类型
import { UploadProps, ElMessage } from 'element-plus'

const $route = useRoute()

//当前页数
let currentPage = ref<number>(1)
//一页展示的个数
let pageSize = ref<number>(3)
//品牌数据
let trademark = ref<any>([])
//总数
let total = ref<number>()
//控制对话框的展示
let dialogFormVisible = ref<boolean>(false)

let ruleFormRef = ref()
// 收集新增品牌的数据
let addedTrademark = reactive<recordsDataType>({
  tmName: '',
  logoUrl: '',
})
//验证品牌名称
const validateTmName = (rule: any, value: any, callBack: any) => {
  if (value.trim().length >= 2 && value.trim().length <= 50) callBack()
  else callBack(new Error('品牌名称长度应为2-50'))
}
//验证品牌logo
const validateLogoUrl = (rule: any, value: any, callBack: any) => {
  if (value) callBack()
  else {
    callBack(new Error('必须上传品牌图片'))
  }
}

let trademarkRules = reactive({
  tmName: [
    {
      required: true,
      min: 2,
      max: 50,
      trigger: 'blur',
      validator: validateTmName,
    },
  ],
  logoUrl: [
    {
      required: true,
      validator: validateLogoUrl,
    },
  ],
})

//获取品牌数据
const getTrademark = async () => {
  const result: TrademarkResponseData = await reqTradeMark(
    currentPage.value,
    pageSize.value,
  )
  if (result.code == 200) {
    total.value = result.data.total
    trademark.value = result.data.records
    // console.log(result)
  }
}
//挂载时获取表格数据
onMounted(async () => {
  //获取品牌数据
  await getTrademark()
})

//当前页数变化的时候重新加载数据
const changeCurrenPage = () => {
  getTrademark()
}

//一页可展示页数变化时重新加载数据
watch(
  () => pageSize.value,
  () => {
    currentPage.value = 1
    getTrademark()
  },
)

//点击添加品牌按钮
const addTrademark = () => {
  dialogFormVisible.value = true
  addedTrademark.logoUrl = ''
  addedTrademark.tmName = ''
  addedTrademark.id = undefined
  //清空校验信息
  ruleFormRef.value?.clearValidate('tmName')
  ruleFormRef.value?.clearValidate('logoUrl')
}

// 修改品牌
const updateTrademark = (row: recordsDataType) => {
  //展示当前品牌数据
  addedTrademark.logoUrl = row.logoUrl
  addedTrademark.tmName = row.tmName
  addedTrademark.id = row.id
  // Object.assign(addedTrademark,row)
  dialogFormVisible.value = true
  //清空校验信息
  ruleFormRef.value?.clearValidate('tmName')
  ruleFormRef.value?.clearValidate('logoUrl')
}
// 删除品牌
const deleteTrademark = async (id: number) => {
  let result = await reqDeleteTrademark(id)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
    //删除之后重新获取数据
    if (trademark.value.length == 1) {
      currentPage.value = currentPage.value - 1
    }
    getTrademark()
  } else {
    ElMessage({
      type: 'success',
      message: '删除失败',
    })
  }
}

//对品牌进行操作的取消按钮
const cancel = () => {
  dialogFormVisible.value = false
}

//对品牌进行操作的确认按钮
const confirm = async () => {
  //表单校验成功才能发送post请求
  await ruleFormRef.value.validate()
  const result: any = await addOrUpdateTrademark(addedTrademark)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: addedTrademark.id ? '修改品牌成功' : '添加品牌成功',
    })
  } else {
    ElMessage({
      type: 'error',
      message: addedTrademark.id ? '修改品牌失败' : '添加品牌失败',
    })
  }
  dialogFormVisible.value = false
  if (!addedTrademark.id) {
    currentPage.value = 1
  }
  getTrademark()
}
// 上传图片之前的钩子
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (
    rawFile.type !== 'image/jpeg' &&
    rawFile.type !== 'image/png' &&
    rawFile.type !== 'image/gif'
  ) {
    ElMessage.error('头像图片应为Jpg/Jpeg/Png/Gif格式！')
    return false
  } else if (rawFile.size / 1024 / 1024 > 4) {
    ElMessage.error('头像大小不应超过4MB！')
    return false
  }
  return true
}

//上传图片成功后的钩子 response是服务器响应  uploadfile是上传文件的相关信息 如文件大小、格式等等
const handleAvatarSuccess: UploadProps['onSuccess'] = (response) => {
  addedTrademark.logoUrl = response.data
}
</script>

<!-- dialog所需的样式 -->
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
